package com.ys.controller.api.overseas;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.entity.overseas.TosProductActive;
import com.ys.entity.overseas.TosProductActiveDescribe;
import com.ys.entity.overseas.TosProductActiveFile;
import com.ys.entity.sys.TbStaticConfig;
import com.ys.entity.sys.YsCol;
import com.ys.enume.overseas.TosProductActiveEnum;
import com.ys.service.overseas.TosProductActiveService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.CheckUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * HW商品listing库
 */
@Controller
@RequestMapping("/api/inter/tosProductActive")
public class ApiInterTosProductActiveController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTosProductActiveController.class);

    @Autowired
    private CommonApiService<TosProductActive> commonApiService;

    @Autowired
    private TosProductActiveService tosProductActiveService;

    @Autowired
    private CheckUtil checkUtil;

    //菜单id
    private Long menuId = MenuId.TOS_ProductActive;

    //权限字符
    private final String PERMISSIONS_VIEW = "tosProductActive:view";
    private final String PERMISSIONS_EDIT = "tosProductActive:edit";
    private final String PERMISSIONS_ADD_BATCH = "tosProductActive:addBatch";


    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TosProductActive setSeachSql(TosProductActive cond)throws Exception{

        cond = tosProductActiveService.searchByOther(cond);
        cond
                .addLeftJoin("TOS_ProductBasis B ON A.ProductCode = B.Code ")//HW商品表
                .addField("B.SignCode AS signCode")//标识编码
                .addField("B.ProductName AS productName")//商品名称

                .addLeftJoin("TOS_PlatformInformation C ON C.Id = B.PlatformId ")//平台信息维护表
                .addField("C.HwChannel AS hwChannel")//渠道
                .addField("C.PlatformCode AS platformCode")//平台
                .addField("C.HwName AS hwName")//区域
                .addField("C.RegionName AS regionName")//站点
                .addField("C.CurrencyCode AS currencyCode")//币种

        .setOrderby("A.UpdateTime DESC");//排序


        //仅查询该运营人-运营公司-选择的商品
        String loginUserId = ShiroUtils.getUserId();
        if(!loginUserId.equals("admin")){
            cond.where("(SELECT count(1) FROM TOS_ProductSelectionItem UA " +
                    "INNER JOIN TOS_ProductSelection UB ON UA.Pid = UB.Id " +
                    "INNER JOIN THR_OperateCompanyApply UC ON UC.Vgsbm = UB.Vgsbm " +
                    "WHERE UA.Code = A.ProductCode AND UC.Cuser = "+loginUserId+") > 0 ");
        }

        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TosProductActive cond,String conditions
    ){
        try {
            cond = setSeachSql(cond);

            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TosProductActive cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);

            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TosProductActive> util = new ExportExcelUtils<>(new TosProductActive());
            String toFilePath = util.exportExcel(listData, listField, "HW商品listing库");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }




    /**
     * 修改
     */
    @RequiresPermissions(PERMISSIONS_EDIT)
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tosProductActiveService.update(params,menuId);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }




    /**
     * 保存批量导入的图片
     */
    @RequestMapping("/saveImgByBatch")
    @ResponseBody
    public R saveImgByBatch(HttpServletRequest request, String dataList){
        try {
            //批量导入
            JSONArray detailJA = JSON.parseArray(dataList);
            tosProductActiveService.saveImgByBatch(detailJA);
            return R.ok();
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 根据日志信息导入
     */
    @RequestMapping("/importInfoFromBatchImportLogByUser")
    @ResponseBody
    public void importInfoFromBatchImportLogByUser(Model model, HttpServletRequest request, HttpServletResponse response
    ){
        try {
            tosProductActiveService.importInfoFromBatchImportLogByUser();
        }catch (Exception e){
            logger.error("出错：",e.getMessage(),e);
        }
    }





}